package com.java.demo.demo;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @auther zhangwj
 * @date 2021/4/21 上午9:59
 */
public class Demo6 {

    public static void main(String[] args) {
        JavaDeveloper javaDeveloper = new JavaDeveloper();
        Developer developer = GlobalProxy.invoke(javaDeveloper, Developer.class);
        developer.code();
    }
}

interface Developer {

    String code();

    String debug(String var);
}

class JavaDeveloper implements Developer {

    @Override
    public String code() {
        System.out.println("我是Java程序员");
        return "我是Java程序员";
    }

    @Override
    public String debug(String var) {
        System.out.println("调试Bug" + var);
        return "调试Bug" + var;
    }
}

class GlobalProxy{

    public static <T> T invoke(Object object, Class<T> tClass) {
        Object result = Proxy.newProxyInstance(object.getClass().getClassLoader(), object.getClass().getInterfaces(), new GlobalInvocationHandler(object));
        return tClass.cast(result);

    }
}

class GlobalInvocationHandler implements InvocationHandler {

    private Object object;

    public GlobalInvocationHandler(Object object) {
        this.object = object;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object result;
        doBefore();
        result = method.invoke(object, args);
        doAfter();
        return result;
    }

    private void doBefore() {
        System.out.println("before method invoke");
    }

    private void doAfter() {
        System.out.println("after method invoke");
    }
}